package com.cmz.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 国际化工具类
 * @version 1.0.0
 * @author cmz
 */
@Slf4j
public class I18nUtils {

    private I18nUtils() {}

    /**
     * 获取指定 bundle 资源
     * @since 1.0.0
     * @param locale     语言区域
     * @param bundleName bundle 名称
     * @return bundle 资源
     */
    public static ResourceBundle getBundle(Locale locale, String bundleName) {
        ResourceBundle resourceBundle = null;

        try {
            resourceBundle = ResourceBundle.getBundle(bundleName, locale);
        } catch (MissingResourceException e) {
            log.warn(e.getLocalizedMessage());
        }

        return resourceBundle;
    }

    /**
     * 获取 bundle 值
     * @since 1.0.0
     * @param locale     语言区域
     * @param bundleName bundle 名称
     * @param key        bundle 消息 key
     * @return bundle 消息（查找不到时，直接返回 bundle key）
     */
    public static String get(Locale locale, String bundleName, String key) {
        try {
            ResourceBundle bundle = getBundle(locale, bundleName);
            if (bundle==null) {
                return key;
            }
            return bundle.getString(key);
        } catch (MissingResourceException e) {
            log.warn("Can't find bundle for key {} from bundle '{}', locale {}", key, bundleName, locale);
            return key;
        }
    }

    /**
     * 获取 bundle 值
     * @since 1.0.0
     * @param locale       语言区域
     * @param bundleName   bundle 名称
     * @param key          bundle 消息 key
     * @param replacements 占位符替换文字
     * @return bundle 消息（查找不到时，直接返回 bundle key）
     */
    public static String get(Locale locale, String bundleName, String key, Object...replacements) {
        String val = get(locale, bundleName, key);

        if (!StringUtils.isEmpty(val)) {
            return String.format(val, replacements);
        }

        return val;
    }

}
